package handler

import (
	"adm-mysql/docs"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/collectors"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"net/http"
)

//	@title			API
//	@version		1.0
//	@description	database admin
//	@contact.name	张贺朋
//	@contact.email	hepeng.zhang@pintec.com
//	@BasePath		/

func NewRouter() *gin.Engine {
	r := gin.Default()
	// 健康检查
	r.GET("/health", HealthHandler)

	// metrics
	r.GET("/metrics", MetricsHandler())

	// cors
	r.Use(cors.Default())

	//  swagger
	docs.SwaggerInfo.BasePath = "/"
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	// database instance
	r.POST("/database/instance/", CreateDBInstance)
	r.DELETE("/database/instance/:id/", DeleteDBInstance)
	r.PUT("/database/instance/", UpdateDBInstance)
	r.GET("/database/instances/", ListDBInstances)
	// database backup
	r.POST("/database/backup/", CreateDBBackup)
	r.DELETE("/database/backup/", DeleteDBBackup)
	r.PUT("/database/backup/", UpdateDBBackup)
	r.GET("/database/backups/", ListDBBackups)

	return r
}

// HealthHandler godoc
//
//	@Summary		health
//	@Description	健康检查
//	@Tags			health
//	@Accept			json
//	@Produce		json
//	@Success		200	{string}	Ok
//	@Router			/health [get]
//
// HealthHandler 健康检查
func HealthHandler(c *gin.Context) {
	c.String(http.StatusOK, "Ok")
}

// MetricsHandler godoc
//
//	@Summary		health
//	@Description	健康检查
//	@Tags			health
//	@Accept			json
//	@Produce		json
//	@Success		200	{string}	Ok
//	@Router			/metrics [get]
//
// MetricsHandler 监控指标
func MetricsHandler() gin.HandlerFunc {
	reg := prometheus.NewRegistry()
	reg.MustRegister(
		collectors.NewGoCollector(),
		collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
	)
	handler := promhttp.HandlerFor(reg, promhttp.HandlerOpts{Registry: reg})
	return func(c *gin.Context) {
		handler.ServeHTTP(c.Writer, c.Request)
	}
}
